$(function(){
	//页面数据加载
	init();
});

function init() {
	$.ajax({
		url:"user/getLoginUser.action",
		type:"post",
		async: false,
		success: function(data) {
			
			//菜单初始化
			menuInit(data.id);
			
			$("#userNameSpan").html(data.userName);
			$("#userRoleSpan").html(getRoleNames(data.id));
			
			//3天内的时间戳是 259200000
			if (data.passwordExpire - moment().format('x') < 259200000) {
				toastr.error("您的密码将在"+moment(data.passwordExpire).fromNow()+"过期，请及时更改密码");
			}else if (data.passwordType == "1") {
				toastr.warning("您的密码是系统设置的临时密码，请及时修改密码");
			}
		},
		error: function() {
			toastr.error("加载登录信息出错，请联系管理员");
		}
	});
	

}


function menuInit(userId) {
	
	//用户所拥有菜单查询
	$.ajax({
		url: "roleMenu/getUserMenuTreeByUserId.action",
		type: "post",
		data: {"userId": userId},
		async: false,
		success: function(data) {
			//console.log(data);
			var menuHtml = getMenuHtml(data);
			//console.log(menuHtml);
			$("#menuLiArea").after(menuHtml);
		},
		error: function() {
			toastr.error("初始化菜单发生错误，请联系管理员");
		}
	});
}

function getMenuHtml(data) {
	var result = '';
	for (var i = 0; i < data.length; i++) {
		//第一级
		result+=	'<li>'
				+		'<a href="#"><i class="fa fa-user"></i> <span class="nav-label">'+data[i].menuName+'</span><span class="fa arrow"></span></a>';
        if (data[i].subMenus!=null && data[i].subMenus.length !=0) {
        	var subMenus = data[i].subMenus;
        	
        	result += 		'<ul class="nav nav-second-level">';
        	for (var j = 0; j < subMenus.length; j++) {
        		//第二级
        		
        		if (subMenus[j].subMenus == null || data[i].subMenus.length ==0) {
        			result +=	'<li><a class="J_menuItem" href="'+subMenus[j].menuUrl+'">'+subMenus[j].menuName+'</a></li>'
        		} else {
        			var subSubMenus = subMenus[j].subMenus;
        			//判断是否是数据接口类型
        			if (isDataInterfaceSubMenu(subSubMenus)) {
        				result +='<li><a class="J_menuItem" href="'+subMenus[j].menuUrl+'">'+subMenus[j].menuName+'</a></li>'
        				continue;
        			}
        			result +=	'<li>'
        					+		'<a href="#">'+subMenus[j].menuName+'<span class="fa arrow"></span></a>'
        					+		'<ul class="nav nav-third-level">';
        			
        			for (var k = 0; k < subSubMenus.length; k++) {
        				//第三级
        				if (subSubMenus[k].menuType == '20171026000005') {
                			continue;
                		}
        				result+=		'<li><a class="J_menuItem" href="'+subSubMenus[k].menuUrl+'">'+subSubMenus[k].menuName+'</a></li>';
        			}
        			result +=		'</ul>';
        			result +=	'</li>';
        		}
        	}
        	result +=		'</ul>';
        } 
        result += '</li>'
	}
	return result;
}
function isDataInterfaceSubMenu(subMenus) {
	for (var i = 0; i < subMenus.length; i++) {
		if (subMenus[i].menuType == '20171026000004') {
			return false;
		}
	}
	return true;
}

